package thread;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

/**
 * 集合常用的API：
 * ArrayList、LinkedList、HashSet、HashMap都不是并发安全的;
 */
public class Demo10AsyncApi {
    public static void main(String[] args) {
        //Collection<Integer> c = new ArrayList<>();
        //Collection<Integer> c = new LinkedList<>();
        //Collection<Integer> c = new HashSet<>();
        //将集合或者Map转为并发安全的,可以使用Collections的对应方法;
        Collection<Integer> c = Collections.synchronizedList(new ArrayList<>());

        Thread t1 = new Thread(){
            public void run(){
                for (int i = 0; i < 1000; i++) {
                    c.add(i);
                }
            }
        };
        Thread t2 = new Thread(){
            public void run(){
                for (int i = 1000; i < 2000; i++) {
                    c.add(i);
                }
            }
        };

        t1.start();
        t2.start();

        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(c.size());
    }
}












